# Create your views here.
from django.http import JsonResponse
from .base import View
from apscheduler.triggers.date import DateTrigger  # 一次性定时任务
from apscheduler.triggers.interval import IntervalTrigger  # 间隔任务
from django.db.models import OuterRef, Subquery
from datetime import datetime, timedelta
import pickle
from uuid import uuid4

from scheduler_package.models import get_job_run_error, get_job_run_history, get_job_run_next, delete_run_history
from scheduler_package.config import JOB_STORE
from scheduler_package.utils.add_task_scheduler import get_add_job_scheduler
from scheduler_package.tasks.task import func

scheduler = get_add_job_scheduler()

# 任务下次运行时间
class JobNextRunTimeAPIView(View):
    authentication_classes = []

    def get(self, request):
        data = get_job_run_next()
        ret = {
            'code': 200,
            'status': 'success',
            'data': data,
        }

        return JsonResponse(ret)


# 任务最近运行历史
class JobRunTimeHistory(View):
    authentication_classes = []

    def get(self, request):
        data = get_job_run_history()
        ret = {
            'code': 200,
            'status': 'success',
            'data': data
        }
        return JsonResponse(ret)


# 任务最近运行错误
class JobRunErrorHistory(View):
    authentication_classes = []

    def get(self, request):
        data = get_job_run_error()
        ret = {
            'code': 200,
            'status': 'success',
            'data': data
        }
        return JsonResponse(ret)


# 删除历史执行数据
class DeleteHistoryRunRecordAPI(View):
    def get(self, request):
        delete_run_history()
        ret = {
            'code': 200,
            'status': 'success',
        }
        return JsonResponse(ret)


class AddSchedulerJobAPI(View):
    def post(self, request):
        '''
        功能：新增定时任务
        :param request:
        :return:
        '''
        job = scheduler.add_job(
            func=func,
            args=(122,322),
            trigger=DateTrigger(run_date=datetime.now()+timedelta(seconds=5)),
            replace_existing=True,
            id=f'new-add-{uuid4()}',
            coalesce=True,  # 合并错过的任务，只执行一次
            name='动态添加的任务'
        )

        ret = {
            'code': 200,
            'status': 'success',
        }
        return JsonResponse(ret)

    def put(self,request):
        job_id = self.data.get('job_id')
        job_store = JOB_STORE.get('default')
        job_list = job_store.get_all_jobs()
        for job in job_list:
            if job_id==job.id:
                #使用添加覆盖的方式来实现修改定时任务
                scheduler.add_job(
                    func=func,
                    args=(200,500),
                    id=job_id,
                    trigger=IntervalTrigger(minutes=2),
                    replace_existing=True,
                    coalesce=True,
                    name='动态更新定时任务'
                )
                return JsonResponse({'code':200,'status':'success'})
        else:
            return JsonResponse({'code':200,'status':'不存在的任务id'})